package com.nopay.cdxphone.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.nopay.cdxphone.Constants;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 更新工具
 * author：jun
 * date：2021/7/1
 */
public class UpdateUtil {

    private static final OkHttpClient okHttpClient  = new OkHttpClient();

    private static final String APK_DIR = Environment.getExternalStorageDirectory().getPath() + "/CDX/";
    private static final String APK_NAME = "cdx.apk";

    public static void downloadApk(OnDownloadApkListener listener) {
        Request request = new Request.Builder().url(Constants.APK_URL).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                if(listener != null) listener.onError(e.getCause());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                File apkDir = new File(APK_DIR);
                if(!apkDir.exists()) apkDir.mkdirs();
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(APK_DIR, APK_NAME);
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        if(listener != null) listener.inProgress(progress);
                    }
                    fos.flush();
                    if(listener != null) listener.onSuccess(file);
                } catch (Exception e) {
                    File file = new File(APK_DIR, APK_NAME);
                    if (file.exists()) {
                        file.delete();
                    }
                    if(listener != null) listener.onError(e.getCause());
                } finally {
                    try {
                        if (is != null) is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null) fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    public interface OnDownloadApkListener {

        void inProgress(int progress);

        void onSuccess(File apkFile);

        void onError(Throwable e);
    }

    public static void install(Activity activity) {
        File apk = new File(APK_DIR, APK_NAME);
        if(apk == null) return;

//        if(canRequestInstallPermission(activity)) {
//            openInstallPermissionSettingActivity(activity);
//            return;
//        }

        if (apk.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri data;
            if(Build.VERSION.SDK_INT >= 24) {
                data = FileProvider.getUriForFile(activity, "cn.cn.myvisualphone.provider", apk);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                data = Uri.fromFile(apk);
            }
            intent.setDataAndType(data, "application/vnd.android.package-archive");
            activity.startActivity(intent);
        }
    }

    private static boolean canRequestInstallPermission(Activity activity) {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !activity.getPackageManager().canRequestPackageInstalls();
    }

    public static final int REQUEST_INSTALL_UNKNOWN_APP_CODE = 0x559E;

    @RequiresApi(api = Build.VERSION_CODES.O)
    private static void openInstallPermissionSettingActivity(Activity activity) {
        Uri uri = Uri.parse("package:" + activity.getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, uri);
        activity.startActivityForResult(intent, REQUEST_INSTALL_UNKNOWN_APP_CODE);
    }
}
